//
//  MVVMView.m
//  PrintJob
//
//  Created by blank on 2017/5/8.
//  Copyright (c) 2017 CYN. All rights reserved.
//

#import "MVVMView.h"
#import "KVOController.h"
#import "MVVMViewModel.h"

@interface MVVMView ()

@property(nonatomic, retain) UILabel *contentLabel;

@property(nonatomic, retain) UIButton *printButton;

@property(nonatomic, retain) MVVMViewModel *mvvmViewModel;

@end

@implementation MVVMView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.contentLabel;
        self.printButton;
    }

    return self;
}


- (void)setMvvmViewModel:(MVVMViewModel *)mvvmViewModel {
    _mvvmViewModel = mvvmViewModel;
    __weak typeof(self) weakSelf = self;
    [self.KVOController observe:mvvmViewModel
                        keyPath:@"contentString"
                        options:(NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew)
                          block:^(id observer, id object, NSDictionary *change) {
                              NSString *newContent = change[NSKeyValueChangeNewKey];
                              [weakSelf.contentLabel setText:newContent];
                          }];
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/



- (UILabel *)contentLabel {
    if (!_contentLabel) {
        _contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 300, 30)];
        [_contentLabel setTextColor:[UIColor blackColor]];
        [_contentLabel setTextAlignment:NSTextAlignmentCenter];
        [self addSubview:_contentLabel];
    }
    return _contentLabel;
}

- (UIButton *)printButton {
    if (!_printButton) {
        _printButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_printButton setFrame:CGRectMake(0, 300, 80, 30)];
        [_printButton setTitle:@"Print" forState:UIControlStateNormal];
        [_printButton addTarget:self
                         action:@selector(printButtonOnClick)
               forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_printButton];
    }
    return _printButton;
}




- (void)printButtonOnClick {
//    if ([_delegate respondsToSelector:@selector(onPrintBtnClick)]) {
//        [_delegate onPrintBtnClick];
//    }
    [self.mvvmViewModel onPrintClick];
}


@end
